<script setup lang="ts">
import { LinkProps } from 'element-plus';
import { genKey, isArr, OptionalMutable } from '../utils';
import { computed } from 'vue';
import { MoreFilled } from '@element-plus/icons-vue';

type TableCellBtn = OptionalMutable<LinkProps> & {
  _k?: number,
  label?: string,
  onClick?: (e: Event) => void
}

const props = defineProps<{
  btns: TableCellBtn | TableCellBtn[]
}>()

const cls = 'ui-cell-btns'

const convertedBtns = computed(() => {
  const btns = (isArr(props.btns) ? props.btns : [props.btns])
    .filter(_ => _)
    .map(_ => ({ ..._, _k: genKey() }))

  return btns.length > 3
    ? { items: btns.slice(0, 2), dropdownItems: btns.slice(2) }
    : { items: btns, dropdownItems: [] }
})

const getBtnProps = (btn: TableCellBtn): TableCellBtn => ({ type: 'primary', underline: false, ...btn })
</script>

<template>
  <div :class="cls">
    <ElLink v-for="_ in convertedBtns.items" :key="_._k" v-bind="getBtnProps(_)">
      {{ _.label }}
    </ElLink>
    <ElDropdown v-if="convertedBtns.dropdownItems.length" trigger="click">
      <ElLink title="更多操作" :underline="false" type="primary" :icon="MoreFilled" />
      <template #dropdown>
        <ElDropdownMenu>
          <ElDropdownItem v-for="_ in convertedBtns.dropdownItems" :key="_._k" :class="`${cls}_dropdown-item`">
            <ElLink v-bind="getBtnProps({ type: 'default', ..._ })">
              {{ _.label }}
            </ElLink>
          </ElDropdownItem>
        </ElDropdownMenu>
      </template>
    </ElDropdown>
  </div>
</template>

<style lang="scss">
.ui-cell-btns {
  display: flex;
  align-items: center;
  justify-content: center;
  > * + * {
    margin-left: 6px;
    &::before {
      content: '';
      display: inline-block;
      height: 1em;
      margin-right: 6px;
      border-left: 1px solid var(--el-border-color-light);
    }
  }
  &_dropdown-item {
    padding: 0 !important;
    .el-link {
      display: block;
      padding: 5px 16px;
      min-width: 88px;
      text-align: center;
    }
  }
}
</style>
